<?php
/**
 * Copyright (c) 不争网络
 *
 * @Description     用户模型.
 * @Author          zhangyong QQ:2315918189
 * @Copyright       Copyright (c) 不争网络 保留所有版权()
 * @Date:           2018/5/4 0004
 * @CreateBy        PhpStorm.
 */
namespace app\common\model;
use think\Model;
class User extends Model{
    protected $selectField = 'id,number,token,account,photo_path,birthday,nickname,openid,sex,add_time,register_type,disabled';


    protected $insert = ['register_time'];
    protected function  setRegisterTimeAttr(){
        return time();
    }

    protected $update = ['update_time'];
    protected function setUpdateTimeAttr(){
        return time();
    }

    protected static function init(){
        //注册之前操作
        self::beforeInsert(function($data){
            //密码加密
            
            //生成token
            $data['token'] = model('user')->createToken(10);
            //生成推荐码
            
        });

        //修改资料前
        self::beforeUpdate(function($data){
            if(isset($data['password']) && $data['password']){
                $data['password'] = md5($data['password']);
            }
            //删除原头像
            if($_FILES){
                $user = model('user')->get(UID);
                if($user['photo_path'] && stripos($user['photo_path'],'http') === false){
                   if(file_exists('.'.$user['photo_path']))
                        unlink('.'.$user['photo_path']);
                }
            }
        });
    }


    /**
     * 创建token
     */
    protected function createToken($length = 8){
        $str = '';
        $char = 'abcdefgihjklmnopqistuvwxyz';
        for($i=0;$i<$length;$i++){
            $str.= $char[mt_rand(0,strlen($char)-1)];
        }
        $str.= time();
        return str_shuffle($str);
    }

    //生成推荐码
    protected function createCode(){
        
        return $code;
    }
    


    /**
     * 用户信息
     * @param $where
     * @param string $field
     */
    public function getUserInfo($where,$field=''){
        if($field === ''){
            $field = $this->selectField;
        }

        $info = $this->where($where)->field($field)->find();
        //对token进行加密

        if(isset($info['token'])){
            $Aes = new \Aes\Aes();
            $info['token'] = $Aes->aes128cbcEncrypt($info['token']);
        }
        //头像
        if(isset($info['photo_path']) && $info['photo_path']){
            if(stripos($info['photo_path'],'http') === false){
                $info['photo_path'] = $info['photo_path'];
            }


        }

        return $info;
    }

    //上传动态图片
    public function upload($img,$path){
        $albums_data = [];
        $uploadPath = config('upload')['path'].$path;  
        //print_r($uploadPath);die;
        if(!is_dir($uploadPath)){
            @mkdir($uploadPath,0777,true);
        }
        $newUpload = $uploadPath.'/'.date('Ymd');
        if(!is_dir($newUpload)){
            mkdir($newUpload,0777,true);
        }
        

        for($i = 0; $i<count($_FILES[$img]['tmp_name']);$i++){
           if($i>count($_FILES[$img]['tmp_name'])){
            break;
           }
            $time = time();
            $base = basename($_FILES[$img]['name'][$i]);
            $pri = strrchr($base,'.');
            $num = $time.rand(11111,99999);
            $newPath = $newUpload.'/'.$num.$pri;
            
            if(move_uploaded_file($_FILES[$img]['tmp_name'][$i],$newPath)){
                array_push($albums_data,'/'.$newPath);
            }else{
                return(['status'=>0,'msg'=>'添加失败']);
            }
        }
        return (['status'=>1,'data'=>$albums_data]);
    }   

  /**
     * [upload 图片上传]
     * @param  string $file     [图片对象]
     * @param  string $path     [上传地址]
     * @param  array  $validate [验证]
     * @return [type]           [description]
 */
    public function uploadphoto($file ,$path = 'evaluate',$type = 0){
        $base_path = './upload/';

        $upload_path = $path == '' ? $base_path : $base_path.$path.'/';
        @mkdir($upload_path,0777);
        $image = \think\Image::open($file);
        if(!in_array($image->type(),['jpg','jpeg','png'])){
            $this->apiReturn(0,'图片格式错误');
        }
        $upload_path .= date('Ymd').'/';

        @mkdir($upload_path,0777);
        $name = md5(date('YmdHis').rand(1000,9999).rand(1000,9999)).'.'.$image->type();
        $name_thumb = md5(date('YmdHis').rand(1000,9999).rand(1000,9999)).'.'.$image->type();
        $image->save($upload_path.$name_thumb);
        if($type == 1){
            $image->thumb(500,500)->save($upload_path.$name);
            $data['image'] = substr($upload_path,1).$name;
            $data['thumb_image'] = substr($upload_path,1).$name_thumb;
            return $data;
        }
        return substr($upload_path,1).$name_thumb;
    }
}